package com.hong.springboot.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketClientCompressionHandler;
import org.springframework.stereotype.Component;

/**
 *
 * 功能描述: 通道初始化值
 *
 * @param:
 * @return:
 * @auther: csh
 * @date: 2021/1/21 11:54
 */
@Component("myWebsocketChannelInitializer")
public class MyWebsocketChannelInitializer extends ChannelInitializer<SocketChannel> {
    private WebsocketClient websocketClient;



    public MyWebsocketChannelInitializer(WebsocketClient websocketClient) {
        this.websocketClient = websocketClient;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        if (websocketClient != null && websocketClient.getSslCtx()!=null) {
            p.addLast(websocketClient.getSslCtx().newHandler(ch.alloc(), websocketClient.getHost(), websocketClient.getPort()));
        }
        //http协议握手
        p.addLast(new HttpClientCodec());
        p.addLast(new HttpObjectAggregator(8192));
        //支持websocket数据压缩
        p.addLast(WebSocketClientCompressionHandler.INSTANCE);
        p.addLast(websocketClient.getHandler());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("传进来的消息:"+(TextWebSocketFrame)msg);
        super.channelRead(ctx, msg);
    }
}